﻿// Copyright (c) egmkang wang. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Gateway
{
    using System;
    using System.Linq;
    using Orleans;
    using Orleans.Concurrency;
    using XServer.GrainInterfaces;
    using XServer.SDK;
    using XServer.SDK.Net;
    using DotNetty.Transport.Channels;

    class GatewayObserver : IGatewayObserver
    {
        public void OnRecvMessage(int destType, long dest, Immutable<byte[]> buffer)
        {
            var bytes = buffer.Value;
            switch ((DestType)destType)
            {
                case DestType.DestType_All:
                    Singleton<ConnManager>.Instance.Sessions.AsParallel().ForAll(item =>
                    {
                        var channel = item.Value.Target as IChannel;
                        if (channel.GetPlayerID() != 0)
                        {
                            channel.WriteAsync(bytes);
                        }
                    });
                    break;
                case DestType.DestType_Server:
                    Singleton<ConnManager>.Instance.Sessions.AsParallel().ForAll(item =>
                    {
                        var channel = item.Value.Target as IChannel;
                        if (channel.GetServerID() == dest && channel.GetPlayerID() != 0)
                        {
                            channel.WriteAsync(bytes);
                        }
                    });
                    break;
                case DestType.DestType_Player:
                    {
                        IChannel channel = PlayerContainer.GetPlayer(dest);
                        if (channel.GetPlayerID() != 0)
                        {
                            channel.WriteAsync(bytes);
                        }
                    }
                    break;
            }

            LoggerProvider.Logger.Info($"{destType}, {dest}");
        }
    }
}
